document.addEventListener('DOMContentLoaded', function() {
    // 元素引用
    const apiStatus = document.getElementById('api-status');
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');

    // 文本生成元素
    const completionPrompt = document.getElementById('completion-prompt');
    const completionMaxTokens = document.getElementById('completion-max-tokens');
    const completionTemperature = document.getElementById('completion-temperature');
    const completionTemperatureValue = document.getElementById('completion-temperature-value');
    const completionSubmit = document.getElementById('completion-submit');
    const completionClear = document.getElementById('completion-clear');
    const completionResult = document.getElementById('completion-result');

    // 对话生成元素
    const chatMessages = document.getElementById('chat-messages');
    const chatInput = document.getElementById('chat-input');
    const chatSubmit = document.getElementById('chat-submit');
    const chatClear = document.getElementById('chat-clear');
    const chatMaxTokens = document.getElementById('chat-max-tokens');
    const chatTemperature = document.getElementById('chat-temperature');
    const chatTemperatureValue = document.getElementById('chat-temperature-value');

    // 图片分析元素
    const imageUpload = document.getElementById('image-upload');
    const imagePreviewContainer = document.getElementById('image-preview-container');
    const imagePreview = document.getElementById('image-preview');
    const imageRemove = document.getElementById('image-remove');
    const imagePrompt = document.getElementById('image-prompt');
    const imageMaxTokens = document.getElementById('image-max-tokens');
    const imageTemperature = document.getElementById('image-temperature');
    const imageTemperatureValue = document.getElementById('image-temperature-value');
    const imageSubmit = document.getElementById('image-submit');
    const imageClear = document.getElementById('image-clear');
    const imageResult = document.getElementById('image-result');

    // API 信息元素
    const requestMethod = document.getElementById('request-method');
    const requestUrl = document.getElementById('request-url');
    const requestBodyContent = document.getElementById('request-body-content');
    const responseStatus = document.getElementById('response-status');
    const responseBodyContent = document.getElementById('response-body-content');

    // 存储聊天历史
    let chatHistory = [];

    // 检查 API 状态
    checkApiStatus();

    // 初始化温度滑块值显示
    completionTemperature.addEventListener('input', function() {
        completionTemperatureValue.textContent = this.value;
    });

    chatTemperature.addEventListener('input', function() {
        chatTemperatureValue.textContent = this.value;
    });

    imageTemperature.addEventListener('input', function() {
        imageTemperatureValue.textContent = this.value;
    });

    // 标签页切换
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');

            // 更新按钮状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            // 更新面板状态
            tabPanes.forEach(pane => pane.classList.remove('active'));
            document.getElementById(`${tabId}-panel`).classList.add('active');
        });
    });

    // 文本生成提交
    completionSubmit.addEventListener('click', async function() {
        const prompt = completionPrompt.value.trim();
        if (!prompt) {
            alert('请输入提示文本');
            return;
        }

        const maxTokens = parseInt(completionMaxTokens.value);
        const temperature = parseFloat(completionTemperature.value);

        try {
            setLoading(true, completionSubmit);
            clearApiInfo();

            const requestBody = {
                prompt,
                maxTokens,
                temperature
            };

            updateRequestInfo('POST', '/api/bailian/completion', requestBody);

            // 使用百炼客户端生成文本
            const data = await BailianClient.generateCompletion(
                prompt,
                maxTokens,
                temperature
            );

            updateResponseInfo(200, data);

            if (data.Data && data.Data.Content) {
                completionResult.innerHTML = `<p>${formatText(data.Data.Content)}</p>`;
            } else {
                completionResult.innerHTML = `<p>API 返回了结果，但没有找到内容。完整响应见下方。</p>`;
            }
        } catch (error) {
            console.error('Error:', error);
            completionResult.innerHTML = `<p class="error">请求失败: ${error.message}</p>`;
            updateResponseInfo(500, { error: { message: error.message } });
        } finally {
            setLoading(false, completionSubmit);
        }
    });

    // 清空文本生成
    completionClear.addEventListener('click', function() {
        completionPrompt.value = '';
        completionResult.innerHTML = '<p class="placeholder">生成的文本将显示在这里...</p>';
        clearApiInfo();
    });

    // 对话提交
    chatSubmit.addEventListener('click', async function() {
        const message = chatInput.value.trim();
        if (!message) {
            alert('请输入消息');
            return;
        }

        // 添加用户消息到界面
        addChatMessage('user', message);
        chatInput.value = '';

        // 添加到历史
        chatHistory.push({ role: 'user', content: message });

        const maxTokens = parseInt(chatMaxTokens.value);
        const temperature = parseFloat(chatTemperature.value);

        try {
            setLoading(true, chatSubmit);
            clearApiInfo();

            const requestBody = {
                messages: chatHistory,
                maxTokens,
                temperature
            };

            updateRequestInfo('POST', '/api/bailian/chat', requestBody);

            // 使用百炼客户端生成聊天回复
            const data = await BailianClient.generateChat(
                chatHistory,
                maxTokens,
                temperature
            );

            updateResponseInfo(200, data);

            if (data.Data && data.Data.Content) {
                const assistantMessage = data.Data.Content;
                addChatMessage('assistant', assistantMessage);
                chatHistory.push({ role: 'assistant', content: assistantMessage });
            } else {
                addChatMessage('assistant', 'API 返回了结果，但没有找到内容。完整响应见下方。');
            }
        } catch (error) {
            console.error('Error:', error);
            addChatMessage('assistant', `请求失败: ${error.message}`);
            updateResponseInfo(500, { error: { message: error.message } });
        } finally {
            setLoading(false, chatSubmit);
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    });

    // 回车发送消息
    chatInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            chatSubmit.click();
        }
    });

    // 清空对话
    chatClear.addEventListener('click', function() {
        chatHistory = [];
        chatMessages.innerHTML = '';
        clearApiInfo();
    });

    // 图片上传和预览
    imageUpload.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 验证是否为图片
            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                imageUpload.value = '';
                return;
            }

            // 验证文件大小
            if (file.size > 5 * 1024 * 1024) { // 5MB
                alert('图片大小不能超过 5MB');
                imageUpload.value = '';
                return;
            }

            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.src = e.target.result;
                imagePreviewContainer.classList.remove('hidden');
            };
            reader.readAsDataURL(file);
        }
    });

    // 移除图片
    imageRemove.addEventListener('click', function() {
        imageUpload.value = '';
        imagePreview.src = '';
        imagePreviewContainer.classList.add('hidden');
    });

    // 图片分析提交
    imageSubmit.addEventListener('click', async function() {
        if (!imageUpload.files || !imageUpload.files[0]) {
            alert('请选择图片');
            return;
        }

        const prompt = imagePrompt.value.trim();
        if (!prompt) {
            alert('请输入提示文本');
            return;
        }

        try {
            setLoading(true, imageSubmit);
            clearApiInfo();

            // 准备表单数据
            const formData = new FormData();
            formData.append('image', imageUpload.files[0]);
            formData.append('prompt', prompt);
            formData.append('maxTokens', imageMaxTokens.value);
            formData.append('temperature', imageTemperature.value);

            // 更新请求信息（简化显示）
            updateRequestInfo('POST', '/api/bailian/image-analysis', {
                prompt,
                maxTokens: parseInt(imageMaxTokens.value),
                temperature: parseFloat(imageTemperature.value),
                image: '[Image Binary Data]'
            });

            // 使用百炼客户端分析图片
            const data = await BailianClient.analyzeImage(formData);

            updateResponseInfo(200, data);

            if (data.Data && data.Data.Content) {
                imageResult.innerHTML = `<p>${formatText(data.Data.Content)}</p>`;
            } else {
                imageResult.innerHTML = `<p>API 返回了结果，但没有找到内容。完整响应见下方。</p>`;
            }
        } catch (error) {
            console.error('Error:', error);
            imageResult.innerHTML = `<p class="error">请求失败: ${error.message}</p>`;
            updateResponseInfo(500, { error: { message: error.message } });
        } finally {
            setLoading(false, imageSubmit);
        }
    });

    // 清空图片分析
    imageClear.addEventListener('click', function() {
        imageUpload.value = '';
        imagePreview.src = '';
        imagePreviewContainer.classList.add('hidden');
        imagePrompt.value = '';
        imageResult.innerHTML = '<p class="placeholder">图片分析结果将显示在这里...</p>';
        clearApiInfo();
    });

    // 辅助函数

    // 检查 API 状态
    async function checkApiStatus() {
        try {
            console.log('Starting API status check...');
            apiStatus.textContent = '检查中...';
            apiStatus.className = '';

            // 检查 BailianClient 是否存在
            if (!window.BailianClient) {
                console.error('BailianClient is not defined!');
                apiStatus.textContent = '客户端错误';
                apiStatus.className = 'error';
                return;
            }

            console.log('BailianClient exists, calling checkStatus...');

            // 使用百炼客户端检查状态
            const statusData = await BailianClient.checkStatus();
            console.log('Status check completed successfully:', statusData);

            apiStatus.textContent = '正常';
            apiStatus.className = 'success';
        } catch (error) {
            console.error('Status check error:', error);
            apiStatus.textContent = '无法连接';
            apiStatus.className = 'error';
        }
    }

    // 添加聊天消息
    function addChatMessage(role, content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${role}-message`;
        messageDiv.innerHTML = formatText(content);
        chatMessages.appendChild(messageDiv);
    }

    // 设置加载状态
    function setLoading(isLoading, button) {
        if (isLoading) {
            button.disabled = true;
            button.innerHTML = '<span class="loading"></span> 处理中...';
        } else {
            button.disabled = false;
            if (button === chatSubmit) {
                button.innerHTML = '发送';
            } else if (button === imageSubmit) {
                button.innerHTML = '分析图片';
            } else {
                button.innerHTML = '生成文本';
            }
        }
    }

    // 更新请求信息
    function updateRequestInfo(method, url, body) {
        requestMethod.textContent = method;
        requestUrl.textContent = url;
        requestBodyContent.textContent = JSON.stringify(body, null, 2);
    }

    // 更新响应信息
    function updateResponseInfo(status, body) {
        responseStatus.textContent = status;
        responseBodyContent.textContent = JSON.stringify(body, null, 2);
    }

    // 清空 API 信息
    function clearApiInfo() {
        requestMethod.textContent = '-';
        requestUrl.textContent = '-';
        requestBodyContent.textContent = '-';
        responseStatus.textContent = '-';
        responseBodyContent.textContent = '-';
    }

    // 格式化文本（简单的换行处理）
    function formatText(text) {
        return text.replace(/\n/g, '<br>');
    }
});
